import os
import requests
from PyQt5.QtGui import QIcon, QPixmap
from PyQt5.QtCore import QSize, Qt, QUrl
from urllib.parse import urlparse
from pathlib import Path
from rss_reader.logger import logger
from rss_reader import RESOURCES_PATH


class IconManager:
    def __init__(self, cache_dir="feed_icons"):
        self.cache_dir = Path(cache_dir)
        self.cache_dir.mkdir(exist_ok=True)
        feed_default_icon_path = RESOURCES_PATH / "feed_default.png"
        self.feed_default_icon = QIcon(str(feed_default_icon_path))
        folder_default_icon_path = RESOURCES_PATH / "folder_default"
        self.folder_default_icon = QIcon(str(folder_default_icon_path))
        feed_all_icon_path = RESOURCES_PATH / "feed_all.png"
        self.feed_all_icon = QIcon(str(feed_all_icon_path))
        starred_icon_path = RESOURCES_PATH / "starred.png"
        self.starred_icon = QIcon(str(starred_icon_path))

    def get_favicon_url(self, site_url):
        """从网站URL推测favicon地址"""
        try:
            parsed = urlparse(site_url)
            return f"{parsed.scheme}://{parsed.netloc}/favicon.ico"
        except:
            return None

    def download_icon(self, icon_url):
        """下载并缓存图标"""
        try:
            response = requests.get(icon_url, timeout=3)
            response.raise_for_status()

            # 生成缓存文件名
            filename = urlparse(icon_url).netloc + ".ico"
            cache_path = self.cache_dir / filename

            with open(cache_path, 'wb') as f:
                f.write(response.content)

            return str(cache_path)
        except Exception as e:
            logger.warning(f"下载图标失败: {str(e)}")
            return None

    def get_icon(self, feed):
        if feed.icon_url and os.path.exists(feed.icon_url):
            return QIcon(feed.icon_url)
        else:
            # 使用默认图标
            return self.feed_default_icon

    def update_icon(self, feed):
        """获取订阅源图标"""
        # 优先使用feed自带的icon_url
        if feed.icon_url:
            if feed.icon_url.startswith('http'):
                cached_path = self.download_icon(feed.icon_url)
                if cached_path and os.path.exists(cached_path):
                    return

        # 次之尝试获取网站favicon
        favicon_url = self.get_favicon_url(feed.url)
        if favicon_url:
            cached_path = self.download_icon(favicon_url)
            if cached_path and os.path.exists(cached_path):
                # 更新feed的icon_url
                feed.icon_url = cached_path
                return